package spring.boot.adminx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import spring.boot.adminx.model.SysRole;
import spring.boot.adminx.model.SysUser;
import spring.boot.adminx.model.SysUserRole;
import spring.boot.adminx.service.SysRoleService;
import spring.boot.adminx.service.SysUserRoleService;
import spring.boot.adminx.service.SysUserService;
import spring.boot.adminx.utils.PageUtils;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/sys/user")
public class SysUserController {

    private static final String DEFAULT_PASSWORD = "12345678";

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;



    @GetMapping("/list")
    @PreAuthorize("hasRole('SYS_USER_LIST')")
    public String list(String beginTime,String endTime,String username, Integer pageNum, Integer pageSize, Model model){
        if (pageNum==null){
            pageNum = 1;
        }
        if (pageSize==null){
            pageSize = PageUtils.PAGE_SIZE;
        }
        Page<SysUser> page = new Page<>(pageNum,pageSize);
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (beginTime!=null&&beginTime.trim().length()>0){
            wrapper.ge("create_time",stringToDate(beginTime));
            model.addAttribute("beginTime",beginTime);
        }
        if (endTime!=null&&endTime.trim().length()>0){
            wrapper.le("create_time",stringToDate(endTime));
            model.addAttribute("endTime",endTime);
        }
        if (username!=null&&username.trim().length()>0){
            wrapper.like("username",username);
            model.addAttribute("username",username);
        }

        IPage<SysUser> sysUserPage = sysUserService.page(page, wrapper);
        model.addAttribute("pages",sysUserPage);

        List<Long> beforePages = new ArrayList<>();
        List<Long> afterPages = new ArrayList<>();
        PageUtils.page(sysUserPage.getPages(),sysUserPage.getCurrent(),beforePages,afterPages);
        model.addAttribute("beforePages",beforePages);
        model.addAttribute("afterPages",afterPages);

        return "system/user/list";
    }

    private Date stringToDate(String time){
        return new SimpleDateFormat("yyyy-MM-dd").parse(time,new ParsePosition(0));
    }

    @PostMapping("enable/{id}/{enable}")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_USER_ENABLE')")
    public boolean enable(@PathVariable String id, @PathVariable String enable){
        UpdateWrapper<SysUser> wrapper = new UpdateWrapper<>();
        wrapper.set("enable",enable);
        wrapper.eq("id",id);
        return sysUserService.update(wrapper);
    }

    @PostMapping("init/password/{id}")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_USER_INIT_PASSWORD')")
    public boolean initPass(@PathVariable String id){
        UpdateWrapper<SysUser> wrapper = new UpdateWrapper<>();
        wrapper.set("password",new BCryptPasswordEncoder().encode(DEFAULT_PASSWORD));
        wrapper.eq("id",id);
        return sysUserService.update(wrapper);
    }

    @GetMapping("/to/add")
    @PreAuthorize("hasRole('SYS_USER_ADD')")
    public String toAdd(Model model){
        List<SysRole> roles = sysRoleService.list();
        model.addAttribute("roles", roles);
        return "system/user/add";
    }

    @PostMapping("insert")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_USER_ADD')")
    public String insert(String username,String phone,String email,String[] roles,String pass){
        return sysUserService.insert(username,phone,email,roles,pass);
    }

    @GetMapping("/to/update/{id}")
    @PreAuthorize("hasRole('SYS_USER_UPDATE')")
    public String toUpdate(@PathVariable String id, Model model){
        SysUser user = sysUserService.getById(id);
        List<SysRole> roles = sysRoleService.list();

        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("sys_user_id",id);
        List<SysUserRole> userRoles = sysUserRoleService.list(wrapper);
        List<Long> roleIds = new ArrayList<>();
        for (SysUserRole userRole : userRoles) {
            roleIds.add(userRole.getSysRoleId());
        }
        model.addAttribute("sysUser",user);
        model.addAttribute("roles", roles);
        model.addAttribute("roleIds", roleIds);
        return "system/user/edit";
    }

    @PostMapping("update")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_USER_UPDATE')")
    public String udpate(String id, String username,String phone,String email,String[] roles){
        return sysUserService.update(id,username,phone,email,roles);
    }

    @GetMapping("/to/update/role/{id}")
    @PreAuthorize("hasRole('SYS_USER_ROLE_UPDATE')")
    public String toUpdateRole(@PathVariable String id, Model model){
        List<SysRole> roles = sysRoleService.list();

        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("sys_user_id",id);
        List<SysUserRole> sysUserRoleList = sysUserRoleService.list(wrapper);
        List<Long> roleIds = new ArrayList<>();
        for (SysUserRole userRole : sysUserRoleList) {
            roleIds.add(userRole.getSysRoleId());
        }
        model.addAttribute("id",id);
        model.addAttribute("roles", roles);
        model.addAttribute("roleIds", roleIds);
        return "system/user/editRoles";
    }

    @PostMapping("role/update")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_USER_ROLE_UPDATE')")
    public String roleUpdate(String id, String[] roles){
        return sysUserService.roleUpdate(id,roles);
    }
}


